# pinyin_field
import os

from config import PINYIN_SOURCE_PATH

# pinyin_field
import os
from config import PINYIN_SOURCE_PATH


def pinyin_source(folder_name, idx):
    """获取拼音数据"""
    pinyin_source_folder_path = os.path.join(PINYIN_SOURCE_PATH, folder_name)
    file_name = f"{folder_name}_page_{idx}.txt"
    pinyin_source_file_path = os.path.join(pinyin_source_folder_path, file_name)
    try:
        with open(pinyin_source_file_path, 'r', encoding='utf-8') as source:
            return source.read()
    except FileNotFoundError:
        print(f"警告：拼音文件不存在 {pinyin_source_file_path}")
        return ""
    except Exception as e:
        print(f"读取拼音文件错误: {e}")
        return ""


def parse_pinyin_data(source):
    """解析拼音数据"""
    if not source:
        return []

    pinyin_lines_all_char = source.strip().split('\n')
    pinyin_lines = []

    for line in pinyin_lines_all_char:
        line = line.strip()
        if '音标：' in line:
            # 分割并获取音标部分
            elems = line.split('音标：')
            # 分割音标并过滤空字符串
            pinyin_elems = [item.strip() for item in elems[1].split(' ') if item.strip()]
            pinyin_lines.append(pinyin_elems)

    return pinyin_lines


def get_pinyin_field(page_idx, sorted_data_translation, folder_name):
    # 创建深拷贝以避免修改原数据
    sorted_data_pinyin = []
    for cluster in sorted_data_translation:
        new_cluster = []
        for line in cluster:
            new_line = [item.copy() for item in line]  # 深拷贝每个项目
            new_cluster.append(new_line)
        sorted_data_pinyin.append(new_cluster)

    # 获取拼音数据
    source = pinyin_source(folder_name, page_idx)
    pinyin_lines = parse_pinyin_data(source)

    print(f"解析到的拼音行: {pinyin_lines}")

    if pinyin_lines:
        # 为每行添加拼音
        for cluster_idx, cluster_data in enumerate(sorted_data_pinyin):

            for line_idx, content_line in enumerate(cluster_data):
                if line_idx>=len(pinyin_lines):
                    break
                pinyin_elem = pinyin_lines[line_idx]
                # 为每个字符添加拼音

                for char_idx, item in enumerate(content_line):
                    if char_idx > len(pinyin_elem) - 1:
                        continue
                    item['pinyin'] = pinyin_elem[char_idx]


    return sorted_data_pinyin


""" 原理代码
def pinyin_source(folder_name, idx):
    # 获取拼音数据
    pinyin_source_folder_path = os.path.join(PINYIN_SOURCE_PATH, folder_name)
    file_name = f"{folder_name}_page_{idx}.txt"
    pinyin_source_file_path = pinyin_source_folder_path + '\\' + file_name
    with open(pinyin_source_file_path, 'r', encoding='utf-8') as source:
        return source.read()


def parse_pinyin_data(source):
    # 解析拼音数据
    pinyin_line = source.split('\n')

    # 获取指定页、对应行的音标
    pinyin_elem_line = []
    for line_elem in pinyin_line:
        if '音标：' in line_elem:
            elems = line_elem.split('音标：')
            # 获取音标且过滤空格
            cur_pinyin_line = [item for item in elems[1].split(' ') if item.strip() != '']
            pinyin_elem_line.append(cur_pinyin_line)

    return pinyin_elem_line


# 通过读取文件来获取拼音字段
def get_pinyin_field(page_idx, sorted_data_translation, folder_name):
    sorted_data_pinyin = sorted_data_translation

    # 获得每页的拼音行列表
    source = pinyin_source(folder_name, page_idx)
    pinyin_elem_line = parse_pinyin_data(source)
    print(pinyin_elem_line)

    # 簇
    line_id = 0
    for cluster_data in sorted_data_pinyin:
        # 列
        for content_lines in cluster_data:
            line_id += 1
            # TODO:在这里将给sorted_data_pinyin创建字段line_id
            # print(f'{line_id}:{content_lines}')
            for index in range(len(content_lines)):
                item = content_lines[index]
                item['pinyin'] = pinyin_elem_line[line_id - 1][index]
                # TODO:将sorted_data_pinyin添加正确

    return sorted_data_pinyin"""
